response.headers.add('X-Script-Version', 'runtime-sql-1.0')

function connect() {
    var data = payload.get().body.toObject()
    if (data.name && data.type && data.uri) {
        var result = SQL.new(data.name, data.type, data.uri, data.cache_size ? data.cache_size : 0)
        if (result == data.name) {
            return okMsg("连接成功")
        }
        return errMsg(507, "连接失败")
    }
    return errMsg(507, '参数错误')
}

function query() {
    var data = payload.get().body.toObject()
    if (data.name && data.sql) {
        var result = SQL.query(data.name, data.sql)
        if (result) {
            return okMsg(result)
        }
        return errMsg(507, "查询失败")
    }
    return errMsg(507, '参数错误')
}

function exec() {
    var data = payload.get().body.toObject()
    if (data.name && data.sql) {
        var result = SQL.exec(data.name, data.sql)
        if (result) {
            return okMsg(result)
        }
        return errMsg(507, "执行失败")
    }
    return errMsg(507, '参数错误')
}

function close() {
    var script = payload.get().query['name[]']
    for (var i = 0; i < script.length; i++) {
        SQL.close(script[i])
    }
    return okMsg("操作成功")
}

function list() {
    return okMsg(SQL.list())
}

function main() {
    // 验证用户权限
    'use api/user/acl/excerpt.js'

    switch (payload.get().method) {
        case 'GET':
            return list()
        case 'POST':
            return query()
        case 'PUT':
            return connect()
        case 'DELETE':
            return close()
        default:
            response.status.notFound()
            return `404 page not found`
    }
}